# MMPlayer Ver 1.0
# Author: Sri
# EMail: sri.appworld@gmail.com
# License: GNU GPL V3

import mc
import os
import sys
import re
import xml.dom.minidom
from xml.dom.minidom import Node

# ================FUNCTION: ======================================
def setupProfile():
	config = mc.GetApp().GetLocalConfig()
	basedir=config.GetValue("media_path")
	videodir=os.path.join(basedir, "Videos")

	print "setupProfile:basedir="+videodir;

	xmldoc = xml.dom.minidom.parse(os.path.join(videodir, "profiles.xml"))

	config = mc.GetApp().GetLocalConfig()
	i=0
	for pnode in xmldoc.getElementsByTagName('profile'):
		profname = "".join(pnode.getAttribute('name'))
		if i==0:
			config.SetValue("plist", str(profname))
			print "setupProfile:making plist:1st="+str(profname);
		else:
			config.PushBackValue("plist", str(profname))
			print "setupProfile:making plist:Nth="+str(profname);
		i += 1
	config.SetValue("profile_size", str(i))
	config.SetValue("profile_index", "0")

# ================FUNCTION: ======================================
def updateProfile(p):
	print "updateProfile p="+str(p);
	config = mc.GetApp().GetLocalConfig()
	config.SetValue("profile_index", str(p))

# ================FUNCTION: ======================================
def getProfileSize():
	config = mc.GetApp().GetLocalConfig()
	sz=int(config.GetValue("profile_size"))
	return sz

# ================FUNCTION: ======================================
def getProfileIndex():
	config = mc.GetApp().GetLocalConfig()
	idx=config.GetValue("profile_index")
	return int(idx)

# ================FUNCTION: ======================================
def getCurProfile():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("profile_index"))
	key="plist{"+str(idx)+"}"
	curProfile=str(config.GetValue(key))
	print "getCurProfile: key="+key+" idx="+str(idx)+" prof="+str(curProfile)

	idx=1
	key="plist{"+str(idx)+"}"
	tmp=config.GetValue(key)
	print "getCurProfile: key="+key+" idx="+str(idx)+" prof="+str(tmp)

	return curProfile

# ================FUNCTION: ======================================
def setupSubProfile():
	config = mc.GetApp().GetLocalConfig()
        basedir=config.GetValue("media_path")
        videodir=os.path.join(basedir,"Videos")
        xmldoc = xml.dom.minidom.parse(os.path.join(videodir,"profiles.xml"))

        config = mc.GetApp().GetLocalConfig()

	curProfile=getCurProfile()

	print "setupSubProfile:curprofile="+curProfile;

        for pnode in xmldoc.getElementsByTagName('profile'):
                profname = "".join(pnode.getAttribute('name'))
		if (curProfile == profname) :
                        config.SetValue("profile", str(profname))
                        print "setupSubProfile:making splist:";

			j=0
			for spnode in pnode.getElementsByTagName('sub_profile') :
				sprofname = "".join(spnode.getAttribute('name'))
				depth=int(spnode.getAttribute('depth'))
				print "setupSubProfile found sprof="+sprofname;
				if j==0 :
					config.SetValue("subprofile", str(sprofname))
					config.SetValue("subprofile_depth", str(depth))
					print "setupSubProfile:making splist:1st="+str(sprofname)+" depth="+str(depth);
				else :
					config.PushBackValue("subprofile", str(sprofname))
					config.PushBackValue("subprofile_depth", str(depth))
					print "setupSubProfile:making splist:Nth="+str(sprofname)+" depth="+str(depth);
				j += 1
			config.SetValue("subprofile_size", str(j))
			config.SetValue("subprofile_index", "0")
			print "setupSubProfile:making splist:sz="+str(j);

# ================FUNCTION: ======================================
def updateSubProf(sp):
	print "updateSubProf sp="+str(sp);
	config = mc.GetApp().GetLocalConfig()
	config.SetValue("subprofile_index", str(sp))

# ================FUNCTION: ======================================
def getSubProfileSize():
	config = mc.GetApp().GetLocalConfig()
	sz=int(config.GetValue("subprofile_size"))
	return sz

# ================FUNCTION: ======================================
def getSubProfileDepth():
	config = mc.GetApp().GetLocalConfig()
	dep=int(config.GetValue("subprofile_depth"))
	return dep

# ================FUNCTION: ======================================
def getSubProfileIndex():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("subprofile_index"))
	return idx

# ================FUNCTION: ======================================
def getCurSubProfile():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("subprofile_index"))
	key="subprofile{"+str(idx)+"}"
	curSubProfile=config.GetValue(key)
	return curSubProfile

# ================FUNCTION: ======================================
def setupLevel3():
	config = mc.GetApp().GetLocalConfig()
	basedir=config.GetValue("media_path")

	basedir=os.path.join(basedir,"Videos")
	basedir=os.path.join(basedir,getCurProfile())
	basedir=os.path.join(basedir,getCurSubProfile())

	print "setupLevel3:basedir="+basedir;

	depth=getSubProfileDepth()

	level3_index=0

	config.SetValue("level3_index", "0")

	if (depth>=1) :
		k=0
		for filename in os.listdir(basedir):
			fullname=os.path.abspath(os.path.join(basedir, filename))
			if (os.path.isdir(fullname)):
				print "L1:"+filename;
				if k==0:
					config.SetValue("level3", str(filename))
					print "setupLevel3:making l3list:1st="+str(filename);
				else:
					config.PushBackValue("level3", str(filename))
					print "setupLevel3:making l3list:Nth="+str(filename);
				k += 1
		config.SetValue("level3_size", str(k))
	else:
		config.SetValue("level3_size", "0")
		print "setupLevel3:getLevel3Size="+config.GetValue("level3_size");

# ================FUNCTION: ======================================
def updateLevel3(l3):
	print "updateLevel3 l3="+str(l3);
	config = mc.GetApp().GetLocalConfig()
	config.SetValue("level3_index", str(l3))

# ================FUNCTION: ======================================
def getLevel3Size():
	config = mc.GetApp().GetLocalConfig()
	sz=int(config.GetValue("level3_size"))
	return sz

# ================FUNCTION: ======================================
def getLevel3Index():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("level3_index"))
	return idx

# ================FUNCTION: ======================================
def getCurLevel3():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("level3_index"))
	key="level3{"+str(idx)+"}"
	curLevel3=config.GetValue(key)
	return curLevel3

# ================FUNCTION: ======================================
def setupLevel4():
	config = mc.GetApp().GetLocalConfig()
	basedir=config.GetValue("media_path")

	basedir=os.path.join(basedir,"Videos")
	basedir=os.path.join(basedir,getCurProfile())
	basedir=os.path.join(basedir,getCurSubProfile())
	basedir=os.path.join(basedir,getCurLevel3())

	print "setupLevel4:basedir="+basedir;

	depth=getSubProfileDepth()

	level4_index=0

	config.SetValue("level4_index", "0")

	if (depth>=2) :
		k=0
		for filename in os.listdir(basedir):
			fullname=os.path.abspath(os.path.join(basedir, filename))
			if (os.path.isdir(fullname)):
				print "L2:"+filename;
				if k==0:
					config.SetValue("level4", str(filename))
					print "setupLevel4:making l4list:1st="+str(filename);
				else:
					config.PushBackValue("level4", str(filename))
					print "setupLevel4:making l4list:Nth="+str(filename);
				k += 1
		config.SetValue("level4_size", str(k))
	else:
		config.SetValue("level4_size", "0")
		print "setupLevel4:getLevel4Size="+config.GetValue("level4_size");

# ================FUNCTION: ======================================
def updateLevel4(l4):
	print "updateLevel4 l4="+str(l4);
	config = mc.GetApp().GetLocalConfig()
	config.SetValue("level4_index", str(l4))

# ================FUNCTION: ======================================
def getLevel4Size():
	config = mc.GetApp().GetLocalConfig()
	sz=int(config.GetValue("level4_size"))
	return sz

# ================FUNCTION: ======================================
def getLevel4Index():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("level4_index"))
	return idx

# ================FUNCTION: ======================================
def getCurLevel4():
	config = mc.GetApp().GetLocalConfig()
	idx=int(config.GetValue("level4_index"))
	key="level4{"+str(idx)+"}"
	curLevel4=config.GetValue(key)
	return curLevel4

# ================FUNCTION: ======================================
def updateButtonLabels():
	config = mc.GetApp().GetLocalConfig()

	#....................................
	lbl=getCurProfile()
	b=mc.GetWindow(14000).GetButton(1000)
	b.SetLabel(lbl)
	print "updateLabels:prof="+lbl;

	#....................................
	lbl=getCurSubProfile()
	b=mc.GetWindow(14000).GetButton(1001)
	b.SetLabel(lbl)
	print "updateLabels:sprof="+lbl;

	#....................................
	sz=getLevel3Size()
	if sz > 0 :
		lbl=getCurLevel3()
	else:
		lbl=""
	b=mc.GetWindow(14000).GetButton(1002)
	b.SetLabel(lbl)
	print "updateLabels:l3="+lbl;

	#....................................
	sz=getLevel4Size()
	if sz>0:
		lbl=getCurLevel4()
	else:
		lbl=""
	b=mc.GetWindow(14000).GetButton(1003)
	b.SetLabel(lbl)
	print "updateLabels:l4="+lbl;

# ================FUNCTION: ======================================
def getRSSPath() :
	config = mc.GetApp().GetLocalConfig()

	basedir=config.GetValue("media_path")
	basedir=os.path.join(basedir, "Videos")

	print "getRSSPath:basedir="+basedir;

	rsspath=""

	#....................................
	lbl=getCurProfile()
	rsspath=lbl

	#....................................
	lbl=getCurSubProfile()
	rsspath=os.path.join(rsspath,lbl)

	#....................................
	sz=int(getLevel3Size())
	if sz > 0 :
		lbl=getCurLevel3()
		rsspath=os.path.join(rsspath,lbl)

	#....................................
	sz=int(getLevel4Size())
	if sz > 0 :
		lbl=getCurLevel4()
		rsspath=os.path.join(rsspath,lbl)

	print "getRSSPath:rsspath="+rsspath;

	return rsspath

# ================FUNCTION: ======================================
def launchVideoBrowser():
	config = mc.GetApp().GetLocalConfig()

	basedir=config.GetValue("media_path")
	basedir=os.path.join(basedir,"Videos")

	rsspath = getRSSPath()

	mediadir=os.path.join(basedir,rsspath)

	print "launchVideoBrowser:mediadir="+mediadir;
	print "launchVideoBrowser:rsspath="+rsspath;

	k=0
	for filename in os.listdir(mediadir):
		fullname=os.path.abspath(os.path.join(mediadir, filename))
		if (os.path.isdir(fullname)):
			print "K1:"+filename;
			k += 1
		else:
			print "K0:"+filename;
			print "K0:"+fullname;

	print "k="+str(k);

	if (k>0):
		updateRSS(mediadir,rsspath)

		params = mc.Parameters()
		params["title"] = "Title"
		params["link"] = "http://127.0.0.1/mmplayer/"+rsspath.replace(os.sep,"_")+"_mmplayer_rss.xml"
		mc.GetApp().ActivateWindow( 14001, params )
	else:
		mc.ShowDialogNotification("No media in path="+mediadir)
		print "No Media: Path="+mediadir;

# ================FUNCTION: ======================================
def updateMediaList():
	config = mc.GetApp().GetLocalConfig()

	basedir=config.GetValue("media_path")
	basedir=os.path.join(basedir,"Videos")

	print "updateMediaList:basedir="+basedir;

	rsspath = getRSSPath()

	mediadir=os.path.join(basedir,rsspath)

	print "updateMediaList:mediadir="+mediadir;

	k=0
	medialst=""
	for filename in os.listdir(mediadir):
		fullname=os.path.abspath(os.path.join(mediadir, filename))
		print "K0:"+filename;
		print "K0:"+fullname;
		if (os.path.isdir(fullname)):
			print "K1:"+filename;
			k += 1
			medialst=medialst+str(k)+". "+filename+"[CR]"
	print "k="+str(k);

	myLabel = mc.GetActiveWindow().GetLabel(101)
	if (k>0):
		myLabel.SetLabel(medialst)
	else:
		medialst="No media found in "+rsspath
		myLabel.SetLabel(medialst)

# ================FUNCTION: ======================================
def launchConfig():
	params = mc.Parameters()
	params["title"] = "Config"
	params["link"] = ""
	mc.GetApp().ActivateWindow( 14002, params )

# ================FUNCTION: ======================================
def launchHelp():
	params = mc.Parameters()
	params["title"] = "Help"
	params["link"] = ""
	mc.GetApp().ActivateWindow( 14003, params )

# ================FUNCTION: ======================================
def gethello():
	return "Hello"

# ================FUNCTION: ======================================
def updateRSS(videodir,rsspath):

	config = mc.GetApp().GetLocalConfig()

	rss_root_folder=config.GetValue("rss_root_folder")
	print "RSS root folder="+rss_root_folder;
	
	print "plt="+sys.platform;

	fname=rss_root_folder+os.sep+"mmplayer"+os.sep+rsspath.replace(os.sep,"_")+"_mmplayer_rss.xml"
	print "updateRSS:write file="+fname;
	xmlf=open(fname, 'w')

	xmlstr="<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
	xmlf.write(xmlstr)
	xmlstr="<rss version=\"2.0\" xmlns:boxee=\"http://boxee.tv/rss\" xmlns:media=\"http://search.yahoo.com/mrss/\">\n"
	xmlf.write(xmlstr)
	xmlstr="<channel>\n"
	xmlf.write(xmlstr)

	xmlstr="<title>Vacation Videos</title>\n"
	xmlf.write(xmlstr)
	xmlstr="<link>rss://127.0.0.1/series.php</link>\n"
	xmlf.write(xmlstr)
	xmlstr="<description>Vacation Videos</description>\n"
	xmlf.write(xmlstr)
	xmlstr="<language>en-us</language>\n"
	xmlf.write(xmlstr)

	dir=videodir
	audiolst=('.mp3', '.wav', '.aud' )
	videolst=('.flv', '.mp4', '.avi', '.mkv', '.asf', '.rmvb', '.m2t', '.m4v', '.mpg', '.mov')
	piclst=['.jpg', '.png', '.bmp', '.tif']

	for root, dirs, files in os.walk(dir):
		if files :
			k=0
			vfcnt=0
			thumb=""
			for f in files:
				if os.path.splitext(f)[1].lower() in piclst:
					if (k==0):
						thumb=f
						k = k+1
				if os.path.splitext(f)[1].lower() in videolst:
					vfcnt = vfcnt + 1

			vfidx=0
			for f in files:
				if os.path.splitext(f)[1].lower() in videolst:
					vfidx = vfidx + 1
					tstart=root.rfind(os.sep)
					tstart = tstart + 1
					xmlstr="<item>\n"
					xmlf.write(xmlstr)

					if (vfcnt>1):
						xmlstr="<title>"+str(vfidx)+". "+root[tstart:]+"</title>\n"
					else:
						xmlstr="<title>"+root[tstart:]+"</title>\n"

					xmlf.write(xmlstr)
					xmlstr="<description>"+root[tstart:]+"</description>\n"
					xmlf.write(xmlstr)
					xmlstr="<pubDate>Mon, 24 Jan 2011 17:01:30 -0800</pubDate>\n"
					xmlf.write(xmlstr)
					xmlstr="<boxee:runtime>7200</boxee:runtime>\n<author>"+root[tstart:]+"</author>\n"
					xmlf.write(xmlstr)

					print "Video="+os.path.join(root, f);
					medianame=os.path.join(root, f)
					if (sys.platform == 'win32') :
						xmlstr="<media:content url=\""+medianame[0:]+"\" type=\"application/x-shockwave-flash\" />\n"
					else:
						xmlstr="<media:content url=\""+medianame[1:]+"\" type=\"application/x-shockwave-flash\" />\n"
					xmlf.write(xmlstr)
            
					if (len(thumb)>0):
						xmlstr="<media:thumbnail url=\""+os.path.join(root, thumb)+"\" />\n"
						xmlf.write(xmlstr)
						print "Thumb="+os.path.join(root, thumb);
					else:
						print "NO THUMB"

					xmlstr="<media:author>Author</media:author>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:category scheme=\"urn:boxee:title-type\">tv</media:category>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:category scheme=\"urn:boxee:episode\"></media:category>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:category scheme=\"urn:boxee:genre\">Genre</media:category>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:category scheme=\"urn:boxee:show-title\">"+rsspath.replace(os.sep,">")+"</media:category>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:category scheme=\"urn:boxee:source\">Source</media:category>\n"
					xmlf.write(xmlstr)
					xmlstr="<media:copyright></media:copyright>\n"
					xmlf.write(xmlstr)
					xmlstr="</item>\n"
					xmlf.write(xmlstr)
	print "-----------------------------------"

	xmlstr="</channel>\n</rss>\n"
	xmlf.write(xmlstr)
	xmlf.close()
